<template>
  <div class="md-viewer">
    <div v-if="rawContent" v-html="compiledMarkdown" class="markdown-body"></div>
    <div v-else>
      <div class="error-message">
        <span class="error-icon">⚠️</span>
        无源码文件
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { marked } from 'marked'

const props = defineProps({
  filePath: {
    type: String,
    required: true
  }
})

const compiledMarkdown = ref('')
const rawContent = ref('')

// 加载Markdown文件
const loadMarkdown = async () => {
  try {
    const response = await fetch(props.filePath)
    rawContent.value = await response.text()
    console.log(rawContent.value);
    
    compileMarkdown()
  } catch (error) {
    console.error('Error loading markdown file:', error)
    rawContent.value = `# Error\nFailed to load markdown file: ${props.filePath}`
    console.log(rawContent.value);
    compileMarkdown()
  }
}

// 编译Markdown并高亮代码
const compileMarkdown = () => {
  marked.setOptions({
    highlight: function (code, lang) {
      const language = hljs.getLanguage(lang) ? lang : 'plaintext'
      return hljs.highlight(code, { language }).value
    },
    langPrefix: 'hljs language-',
    breaks: true,
    gfm: true
  })

  compiledMarkdown.value = marked(rawContent.value)
  nextTick(() => {
    addCopyButtons()
  })
}

// 添加复制按钮
const addCopyButtons = () => {
  document.querySelectorAll('pre').forEach((preBlock) => {
    // 如果已经有复制按钮，跳过
    if (preBlock.querySelector('.copy-btn')) return

    const copyBtn = document.createElement('button')
    copyBtn.className = 'copy-btn'
    copyBtn.textContent = '复制'
    copyBtn.addEventListener('click', () => {
      const codeBlock = preBlock.querySelector('code')
      if (codeBlock) {
        copyToClipboard(codeBlock.textContent)
        copyBtn.textContent = '已复制!'
        setTimeout(() => {
          copyBtn.textContent = '复制'
        }, 2000)
      }
    })

    const btnContainer = document.createElement('div')
    btnContainer.className = 'copy-btn-container'
    btnContainer.appendChild(copyBtn)

    preBlock.appendChild(btnContainer)
  })
}

// 复制到剪贴板
const copyToClipboard = (text) => {
  const textarea = document.createElement('textarea')
  textarea.value = text
  document.body.appendChild(textarea)
  textarea.select()
  document.execCommand('copy')
  document.body.removeChild(textarea)
}

// 监听文件路径变化
watch(() => props.filePath, loadMarkdown)

// 初始化加载
onMounted(loadMarkdown)
</script>

<style scoped>
.md-viewer {
  position: relative;
  max-width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 0 0 8px 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.markdown-body {
  box-sizing: border-box;
  min-width: 200px;
  max-width: 1100px;
  margin: 0 auto;
  padding: 16px;
  border-top: 1px dashed #666;
  border-bottom: 1px dashed #666;
}

@media (max-width: 767px) {
  .markdown-body {
    padding: 15px;
  }
}
</style>

<style>
/* 代码块样式 */
.markdown-body pre {
  position: relative;
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 16px;
  overflow: auto;
  max-height: 500px;
  /* 限制代码块最大高度 */
}

/* 复制按钮样式 */
.copy-btn-container {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 2;
}

.copy-btn {
  background-color: #f6f8fa;
  border: 1px solid #d1d5da;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.copy-btn:hover {
  background-color: #e1e4e8;
}

/* 确保代码块有足够的空间 */
.markdown-body pre code {
  display: block;
  padding-top: 16px;
  /* 为复制按钮留出空间 */
  overflow-x: auto;
}
</style>